/**
 * Module dependencies.
 */
'use strict';
var logger = require('koa-logger'),
  route = require('koa-route'),
  parse = require('co-body'),
  koa = require('koa'),
  render = require('./lib/render'),
  factory = require('./lib/factory'),
  schedule = require('node-schedule'),
  co = require("co"),
  config = require('./config/global');



co(function*() {
  // Runs immedischeduleJobately on startup
  schedule.scheduleJob(config.cron, function scheduledJob() {
    co(siteTriger());
  });

});

var app = koa();
// "database"


// middleware

app.use(logger());



// route middleware

app.use(route.get('/', home));
//app.use(route.get('/weixin/:id', weixin));
app.use(route.get('/site', site));



// route definitions

/**
 * home
 */

function* home() {
  this.body = yield render('home', {
    count: 1
  });
}


/**
 * weixin-rss builder
 */

function* weixin(id) {
  try {
    var handler = factory.create('weixin', id);
    var data = yield handler.getData();
    this.type = 'text/xml; charset=UTF-8';
    this.body = yield render('weixin', {
      rss: data
    });
  } catch (err) {
    console.log(err);
    this.body = err.message;
  }
}

//定时抓取页面
function* siteTriger() {
  try {
    var handler = factory.create('site');
    yield handler.fetchData();
  } catch (err) {
    logger.error('ERROR fetch triger:\n', err);
  }
}

function* site() {
  try {
    var handler = factory.create('site');
    var data = yield handler.getData();

    this.type = 'text/xml; charset=UTF-8';
    this.body = yield render('site', {
      rss: data
    });
  } catch (err) {
    console.log(err);
  }
}


// listen
app.listen(config.port, config.ipaddress);
console.log('listening on ip ' + config.ipaddress + ',port ' + config.port);